layui.use(['form', 'jquery'], function () {

    const form = layui.form,
        $ = layui.jquery;

    const userCode = localStorage.getItem("loginUserCode");
    const id = sessionStorage.getItem("wordId");
    findById(id);

    /**
     * 查询单个
     * @param id
     */
    function findById(id) {

        let result = commonAjax('/word/findById',{id:id},'get');
        setData(result.data);
    }

    /**
     * 赋值
     */
    function setData(data) {
        $('#id').val(data.id);
        $('#chinese').val(data.chinese);
        $('#english').val(data.english);
        form.render();
    }

    /**
     * 保存
     */
    form.on('submit(commit)', function (data) {
        let formData = JSON.stringify(data.field);

        let result = commonAjax('/word/update?userCode='+userCode,formData,'post');
        if (result.code === 200) {
            layerMsgSaveSuccess();
        } else if (result.code === 404) {
            layer.msg("该单词您已经添加过了", {icon: 5, time: 2000, shade: 0.4});
        }else {
            layerMsgSaveFail();
        }

        return false;
    });

});